import { saveOrderApi, updateOrderApi } from "@/api/waybillManagement/insurance/placeOrder";
import { message } from "ant-design-vue";

export default function OperationHook(state: any) {
  const { formState, loading, formRef, emit, passData, type } = state;

  const onSubmit = () => {
    formRef.value.validate().then(() => {
      let requestFn;
      let params;

      if (type.value === 1) {
        params = {
          waybillId: passData.value.waybillId,
          orderCompanyReqList: formState.orderCompanyReqList
        };
        requestFn = saveOrderApi;
      } else {
        params = {
          id: passData.value.id,
          ...formState.orderCompanyReqList[0]
        };
        requestFn = updateOrderApi;
      }

      loading.value = true;
      requestFn(params)
        .then((res: any) => {
          const { code } = res;
          if (code === 200) {
            message.success("操作成功!");
            emit("submit");
          }
        })
        .finally(() => {
          loading.value = false;
        });
    });
  };
  const resetForm = () => {
    formRef.value.resetFields();
    emit("update:visible", false);
  };

  const addHandle = () => {
    formState.orderCompanyReqList.push({
      insuranceCompanyId: "",
      insuranceAmount: "",
      insuranceType: "",
      insuranceNature: "",
      insuranceRemark: ""
    });
  };
  const deleteHandle = (index: number) => {
    formState.orderCompanyReqList.splice(index, 1);
  };
  return {
    resetForm,
    onSubmit,

    addHandle,
    deleteHandle
  };
}
